'use strict';

const Controller = require('egg').Controller;
class SearchController extends Controller {
  // 全文搜索
  async search(){
    const { app,ctx } = this;
    if(app.validator.validate({keyword:'string'},ctx.query)){
      return ctx.helper.resSuccess(null);
    }
    let musicList = await ctx.service.user.music.search(ctx.query);
    let playlistList = await ctx.service.user.playlist.search(ctx.query);
    let albumPlayNum = await ctx.service.user.album.search(ctx.query);
    albumPlayNum.sort((a,b)=>{return b.playNum-a.playNum});
    let albumList = albumPlayNum.slice(0,5);
    let starPlayNum = await ctx.service.user.star.search(ctx.query);
    starPlayNum.sort((a,b)=>{return b.playNum-a.playNum});
    let starList = starPlayNum.slice(0,5);
    for(let i of musicList){
      if(i.dataValues.isCollection){
        i.dataValues.isCollection = true;
      }else{
        i.dataValues.isCollection = false;
      }
      if(i.dataValues.isLikes){
        i.dataValues.isLikes = true;
      }else{
        i.dataValues.isLikes = false;
      }
    }
    for(let i of playlistList){
      if(i.dataValues.isCollection){
        i.dataValues.isCollection = true;
      }else{
        i.dataValues.isCollection = false;
      }
      if(i.dataValues.isLikes){
        i.dataValues.isLikes = true;
      }else{
        i.dataValues.isLikes = false;
      }
      try{
        i.dataValues.musicNum = JSON.parse(i.dataValues.musics).length;
      }catch(e){
        i.dataValues.musicNum = 0;
      }
      delete i.dataValues.musics;
    }
    for(let i of albumList){
      if(i.dataValues.isCollection){
        i.dataValues.isCollection = true;
      }else{
        i.dataValues.isCollection = false;
      }
      if(i.dataValues.isLikes){
        i.dataValues.isLikes = true;
      }else{
        i.dataValues.isLikes = false;
      }
    }
    for(let i of starList){
      if(i.dataValues.isCollection){
        i.dataValues.isCollection = true;
      }else{
        i.dataValues.isCollection = false;
      }
      if(i.dataValues.isLikes){
        i.dataValues.isLikes = true;
      }else{
        i.dataValues.isLikes = false;
      }
    }
    return ctx.helper.resSuccess({
      musicList,
      playlistList,
      albumList,
      starList
    });
  }
}

module.exports = SearchController;
